# Dir Rules
OBJDIRS += kern

# extra includes and flags
KERN_CFLAGS	:= -nostdinc
KERN_LDFLAGS	:= $(LDFLAGS) -T kern/linker.ld -nostdlib

# loader must be first
KERN_SRC :=	kern/loader.S

# all sources
KERN_SRC +=	kern/init.c		\
		kern/monitor.c		\
		kern/vm.c		\
		kern/debug.c		\
		kern/swtch.S		\
		kern/trap.c		\
		kern/trapentry.S	\
		kern/sched.c		\
		kern/proc.c		\
		kern/spinlock.c		\
		kern/loadsegregs.S

KERN_LIB_SRC :=	lib/string.c	\
		lib/pool.c

KERN_EXE :=	user/init

# sources -> object files
KERN_OBJ :=	$(patsubst %.c, $(OBJDIR)/%.o, $(KERN_SRC))
KERN_OBJ :=	$(patsubst %.S, $(OBJDIR)/%.o, $(KERN_OBJ))
KERN_OBJ +=	$(OBJDIR)/kern/vectors.o
KERN_OBJ +=	$(OBJDIR)/kern/pgdir.o

KERN_LIB_OBJ :=	$(patsubst %.c, $(OBJDIR)/%.o, $(KERN_LIB_SRC))

KERN_EXE :=	$(patsubst %, $(OBJDIR)/%, $(KERN_EXE))

SRCS 	+= $(KERN_SRC)

# targets for all .c files
$(OBJDIR)/kern/%.o: kern/%.c
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $(KERN_CFLAGS) -I$(INC) -c -o $@ $<

# targets for all .S files
$(OBJDIR)/kern/%.o: kern/%.S
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $(KERN_CFLAGS) -I$(INC) -c -o $@ $<

$(OBJDIR)/kern/vectors.o: $(SCRIPTS)/gen_interrupt_vec.py
	@mkdir -p $(@D)
	@$(SCRIPTS)/gen_interrupt_vec.py > $(SRC)/kern/vectors.S
	$(CC) $(CFLAGS) $(KERN_CFLAGS) -I$(INC) -c -o $@ $(SRC)/kern/vectors.S
	
$(OBJDIR)/kern/pgdir.o: $(SCRIPTS)/gen_init_pgdir.py
	@mkdir -p $(@D)
	@$(SCRIPTS)/gen_init_pgdir.py > $(SRC)/kern/pgdir.S
	$(CC) $(CFLAGS) $(KERN_CFLAGS) -I$(INC) -c -o $@ $(SRC)/kern/pgdir.S
	
# create the kernel bin
$(OBJDIR)/kern/kernel.bin: $(KERN_OBJ) $(KERN_EXE) $(KERN_LIB_OBJ) $(SRC)/kern/linker.ld
	@mkdir -p $(@D)
	$(LD) $(KERN_LDFLAGS) -o $@ $(KERN_OBJ) $(KERN_LIB_OBJ) -b binary $(KERN_EXE)
	$(OBJDUMP) -S $@ > $@.asm
	$(NM) -n $@ > $@.sym

# create the kernel floppy disk
$(OBJDIR)/kern/kernel.floppy: $(OBJDIR)/kern/kernel.bin $(OBJDIR)/boot/grub/boot
	cat $(OBJDIR)/boot/grub/boot $(OBJDIR)/kern/kernel.bin > $@

$(OBJDIR)/kern/kernel.harddisk: $(OBJDIR)/kern/kernel.bin
	@dd if=/dev/zero of=$@ bs=4k count=1024 2>/dev/null 2> /dev/null
	@mkfs.vfat $@
	@syslinux $@
	@mcopy -i $@ /usr/lib/syslinux/mboot.c32 ::mboot.c32
	@mcopy -i $@ $(OBJDIR)/kern/kernel.bin ::kernel.bin
	@echo '\nTIMEOUT 1\nDEFAULT mboot.c32 kernel.bin \n'| mcopy -i $@ - ::syslinux.cfg

kern-bin: $(OBJDIR)/kern/kernel.bin
kern-floppy: $(OBJDIR)/kern/kernel.floppy
kern-harddisk: $(OBJDIR)/kern/kernel.harddisk


